var mysql = require("mysql"); //加载响应的模块

// 创建连接池
var connection = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '',
    prot: 3306,
    database: 'reality',
    timezone: "08:00"
})

var doSQL = (sql, parmas = []) => {
    return new Promise((resolve, reject) => {
        // 从创建的连接池中获取到连接
        connection.getConnection((err, connect) => {
            if (err) {
                reject(err)
            } else {
                connect.query(sql, parmas, function (err, data, fileds) {
                    // connection.realease()方法释放数据库连接
                    connect.release()
                    resolve({
                        err,
                        data,
                        fileds
                    })
                })
            }
        })
    })
}


//登录成功返回
var handerdata = (data) => {
    return JSON.stringify({
        success: true,
        code: 20000,
        messeng: "退出成功",
        data: data
    })
}

// 数据请求成功
var handerResult = (data, total) => {
    return JSON.stringify({
        success: 'true',
        errcode: 0,
        code: 20000,
        msg: '数据请求成功',
        data: data,
        total,
    })
}

// 数据请求成功
var handeruser = (data, user) => {
    return JSON.stringify({
        success: 'true',
        errcode: 0,
        code: 20000,
        msg: '数据请求成功',
        data: data,
        user,
    })
}


// 登录用户名与密码不匹配
var noHanderResult = (data) => {
    return JSON.stringify({
        success: "true",
        errcode: 444, //用户名和密码错误
        msg: "用户名与密码不匹配",
        data: {
            status: 222
        }
    })
}


// 数据请求失败
var errorResult = (data) => {
    return JSON.stringify({
        success: false,
        errcode: 0,
        msg: "数据请求失败",
        data
    })
}

// 数据删除成功
var handerDelete = (data) => {
    return {
        code: 20000,
        mesg: "数据删除成功"
    }
}

var db = {
    doSQL: doSQL,
    handerdata: handerdata,
    handerResult: handerResult,
    errorResult: errorResult,
    handerDelete: handerDelete,
    noHanderResult: noHanderResult,
    handeruser: handeruser
}

module.exports = db